<template>
    <div id="add-edit-noticeInfo">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="769px" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="auto" :rules="rules">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('mHQbqtifZo7Ua2oSixm7')" prop="title">
                            <el-input v-model="ruleForm.title" :placeholder="$t('kCzQf1On_1eAjYOjT3lR')" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('9cBha6zd6bH8xG1Ob6Jlo')" prop="type">
                            <el-radio-group v-model="ruleForm.type" class="ml-4">
                                <el-radio 
                                    border 
                                    v-for="item in typeDictTypeArr"
                                    :key="item.value"
                                    :label="item.code"
                                    size="large"
                                >{{ item.value }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item :label="$t('uzJl3ocbrUsA00dTplP7V')">
                            <div ref="editorElem"></div>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item :label="$t('gGGj2I0OshGrazvUiwKur')" prop="noticeUserIdList">
                            <el-select
                                v-model="ruleForm.noticeUserIdList"
                                multiple
                                filterable
                                :placeholder="$t('aeUcRnys3rlzzfadq9DuM')"
                                style="width: 240px"
                                >
                                <el-option
                                    v-for="item in filterOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">{{ $t('gJikJmcygxvlVId7NvzSu') }}</el-button>
                <el-button type="danger" :disabled="repeatDis" @click="submitForm( ruleFormRef , 0 )">{{ $t('k1CqyL3gWhUucQGrPft6o') }}</el-button>
                <el-button type="primary" :disabled="repeatDis" @click="submitForm( ruleFormRef , 1 )">{{ $t('gqJcy4dxe2XtQuHdn33Fe') }}</el-button>
            </template>
        </el-dialog>
        
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch , Ref , getCurrentInstance } from 'vue'
import { FormInstance, FormRules , ElMessage, ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus'
import { sysFileInfoUploadEditor , sysUserSelector , sysNoticeAdd , sysNoticeEdit } from '/@/api/manage/manage'
import E from "wangeditor" //导入组件
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
const { proxy } = useCurrentInstance();
const $t = proxy.$t;
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    id: Number | String, // id
    title: String, // 标题
    type: any, // 类型
    noticeUserIdList: any,
}
export default defineComponent( {
    name: 'add-edit-noticeInfo',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        },
        typeDictTypeDropDown: {
            type: Array,
            default: []
        }
    },
    setup(props,ctx){
        const { proxy } = getCurrentInstance() as any
        const _this = proxy
        const titleCon = ref()
        const ruleFormRef = ref()
        const typeDictTypeArr = ref()
        const editorUploadConfig = ref()
        const filterOption = ref()

        editorUploadConfig.value = {
            method: 'http',
        }
        const editor = ref()
        const editorElem: Ref = ref(null)

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            title: [
				{ required: true, message: $t('v23ZzTFq6qJ03lJ1cPyIv'), trigger: 'blur' },
			],
            type: [
				{ required: true, message: $t('xmWePfvyDb14xFptIgCn1'), trigger: 'blur' },
			],
            noticeUserIdList: [{
                required: true, message: $t('tBxl8Hkq7LqLdf9cmtJ8Y'), trigger: 'change'
            }]
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = ( formEl: FormInstance | undefined , num: number ) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    const setObj = toRaw(state.ruleForm)
                    let setArr: any[] = []
                    if(editor.value.txt.html() === ''){
                        ElMessage({
                            message: $t('wZRvkxqWz0ItVqJ7bJAf'),
                            type: 'warning',
                            duration: 1000,
                        })
                        return
                    }
                    if(setObj.noticeUserIdList.length !== 0){
                        setObj.noticeUserIdList.map((i:any) => {
                            setArr.push(String(i))
                        })
                    }
                    let param = {
                        id: String(setObj.id),
                        title: setObj.title,
                        status: num,
                        type: parseInt(setObj.type),
                        content: editor.value.txt.html(),
                        noticeUserIdList: setArr
                    }

                    if(setObj.id === ''){
                        const { id , ...paramObj } = param
                        let res:any = await sysNoticeAdd(paramObj)
                        if(res.success){
                            state.repeatDis = true
                            ctx.emit('controlUseClick')
                            ctx.emit('updateData')
                        }else{
                            ctx.emit('controlUseClick')
                        }
                    }else{
                        let res:any = await sysNoticeEdit(param)
                        if(res.success){
                            state.repeatDis = true
                            ctx.emit('controlUseClick')
                            ctx.emit('updateData')
                        }else{
                            ctx.emit('controlUseClick')
                        }
                    }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        const readBlobAsDataURL = (blob:any, callback:any) => {
            const a = new FileReader()
            a.onload = function (e:any) { callback(e.target.result) }
            a.readAsDataURL(blob)
        }

        /*** ConfigRichText 定义富文本编辑器 */
        const ConfigRichText = () => {
            editor.value = new E(editorElem.value)
            editor.value.customConfig = editor.value.customConfig ? editor.value.customConfig : editor.value.config
            editor.value.customConfig.debug = true;
            editor.value.customConfig.uploadImgMaxLength = 5

            editor.value.customConfig.customUploadImg = async (files:any, insert:any) => {
                if (editorUploadConfig.value.method === 'custom') {
                    files.forEach((file:any) => {
                    var fileUrl = URL.createObjectURL(file)
                        insert(fileUrl)
                    })
                }

                if (editorUploadConfig.value.method === 'base64') {
                    files.forEach((file:any) => {
                        readBlobAsDataURL(file, function (dataurl:any) {
                            insert(dataurl)
                        })
                    })
                }

                if (editorUploadConfig.value.method === 'http') {
                    const formData = new FormData()
                    files.forEach((file:any) => {
                        formData.append('file', file)
                    })
                    await sysFileInfoUploadEditor(formData).then((res:any) => {
                        console.log(import.meta.env.VITE_API_URL + '/' + res.data,'res')
                        if (res.success) {
                            insert(import.meta.env.VITE_API_URL + '/' + res.data)
                        } else {
                            ElMessage({
                                type: 'warning',
                                message: $t('rqabJxcwxDuDxBu6UM2t') + res.message,
                                duration: 1000
                            })
                        }
                    }).catch((err:any) => {
                        ElMessage({
                            type: 'warning',
                            message: $t('wlPb4dr3AsdZ3RfFoTJo') + err.message,
                            duration: 1000
                        })
                    })
                }
            }
            editor.value.create() // 生成编辑器
            editor.value.txt.text(_this.value) // 生成编辑器
            _this.$emit('oninit', editor.value)
        }

        /*** GetUseInfo 获取用户信息 */
        const GetUseInfo = async () => {
            try {
                let res: { data: any[] } = await sysUserSelector()
                filterOption.value = res.data
            } catch (err) {}
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                setTimeout(() => {
                    ConfigRichText()
                },10)
                typeDictTypeArr.value = toRaw(props.typeDictTypeDropDown)
                state.repeatDis = false
                if(props.repairInfo !== ''){
                    titleCon.value = $t('hsGdNuzzcv88tnFtvx5Dz')
                    let setTime = setInterval(() => {
                        state.ruleForm.id = JSON.parse(props.repairInfo).id
                        state.ruleForm.title = JSON.parse(props.repairInfo).title
                        state.ruleForm.type = String(JSON.parse(props.repairInfo).type)
                        state.ruleForm.noticeUserIdList = []
                        editor.value.txt.html(JSON.parse(props.repairInfo).content)
                        clearInterval(setTime)
                    },20)
                }else{
                    titleCon.value = $t('fk5zpzIgL5t2mvU8hJd2t')
                    state.ruleForm = {
                        id: '',
                        title: '',
                        type: '',
                        noticeUserIdList: [],
                    }
                }
                GetUseInfo()
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            typeDictTypeArr,
            editorElem,
            filterOption
        }
    },
} )
</script>
<style scoped lang="scss">
    .ml-4{
        .el-radio{
            height: 32px;
        }
    }
    :deep(.el-select){
        width: 100% !important;
    }
</style>